<template>
  <div class="ck-report">
    <div class="toolbar">
      <el-radio-group v-model="quickRange" size="small" @change="onQuickRange">
        <el-radio-button label="all">全部</el-radio-button>
        <el-radio-button label="today">今日</el-radio-button>
        <el-radio-button label="yesterday">昨日</el-radio-button>
        <el-radio-button label="week">本周</el-radio-button>
        <el-radio-button label="month">本月</el-radio-button>
        <el-radio-button label="custom">自定义</el-radio-button>
      </el-radio-group>
      <el-date-picker
        v-model="dateRange"
        type="datetimerange"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        value-format="YYYY-MM-DD HH:mm:ss"
        :disabled="quickRange !== 'custom'"
        style="margin-left:12px;width: 420px"
      />
      <el-input v-model="query.orderNo" placeholder="出库单号" style="width:160px;margin-left:12px" clearable />
      <el-input v-model="query.customerName" placeholder="客户名称" style="width:160px;margin-left:12px" clearable />
      <el-input v-model="query.contactPerson" placeholder="经办人" style="width:140px;margin-left:12px" clearable />
      <el-input v-model="query.createUserName" placeholder="制单人" style="width:140px;margin-left:12px" clearable />
      <el-input v-model="query.outType" placeholder="出库类型" style="width:140px;margin-left:12px" clearable />
      <el-input v-model="query.warehouseName" placeholder="仓库名称" style="width:160px;margin-left:12px" clearable />
      <el-input v-model="query.goodsOrCategory" placeholder="物品/类别" style="width:160px;margin-left:12px" clearable />
      <el-button type="primary" style="margin-left:12px" @click="loadData(1)">查询</el-button>
      <el-button @click="reset">重置</el-button>
      <el-button @click="onExport">导出</el-button>
      <el-button @click="loadData()">刷新</el-button>
    </div>

    <div class="cards">
      <el-card class="card" shadow="never">
        <div class="num">{{ stats.ordersCount }}</div>
        <div class="label">出库单数量</div>
      </el-card>
      <el-card class="card" shadow="never">
        <div class="num">{{ stats.goodsQuantity }}</div>
        <div class="label">出库货品数量</div>
      </el-card>
      <el-card class="card" shadow="never">
        <div class="num">{{ formatMoney(stats.goodsAmount) }}</div>
        <div class="label">出库货品金额</div>
      </el-card>
    </div>

    <el-table :data="tableData" border style="width: 100%" height="560">
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="billNo" label="出库单号" width="160" />
      <el-table-column prop="bizTime" label="出库时间" width="170" />
      <el-table-column prop="outType" label="出库类型" width="120" />
      <el-table-column prop="customerName" label="客户名称" width="160" />
      <el-table-column prop="goodsName" label="物品名称" min-width="200" />
      <el-table-column prop="warehouseName" label="仓库" width="140" />
      <el-table-column prop="quantity" label="数量" width="100" />
      <el-table-column prop="amount" label="金额" width="120" />
      <el-table-column prop="operatorName" label="经办人" width="120" />
      <el-table-column prop="makerName" label="制单人" width="120" />
      <el-table-column prop="deptName" label="所在部门" width="120" />
      <el-table-column prop="makeTime" label="制单时间" width="170" />
      <el-table-column prop="auditorName" label="审核人" width="120" />
      <el-table-column prop="auditTime" label="审核时间" width="170" />
      <el-table-column prop="remark" label="备注" min-width="160" />
    </el-table>

    <div class="pager">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        v-model:current-page="page"
        v-model:page-size="pageSize"
        @size-change="loadData(1)"
        @current-change="loadData"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { ref, reactive, watch } from 'vue'
import { fetchOutFlowPage, fetchOutFlowStats, type GetOutFlowInput } from '/@/api/report/ck'

const tableData = ref<any[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)

const quickRange = ref<'all'|'today'|'yesterday'|'week'|'month'|'custom'>('month')
const dateRange = ref<[string, string] | null>(null)

const query = reactive<{ orderNo?: string; customerName?: string; contactPerson?: string; createUserName?: string; outType?: string; warehouseName?: string; goodsOrCategory?: string }>({})

function computeRange() {
  const now = dayjs()
  switch (quickRange.value) {
    case 'all':
      return null
    case 'today':
      return [now.startOf('day').format('YYYY-MM-DD HH:mm:ss'), now.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
    case 'yesterday': {
      const y = now.subtract(1, 'day')
      return [y.startOf('day').format('YYYY-MM-DD HH:mm:ss'), y.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
    }
    case 'week':
      return [now.startOf('week').format('YYYY-MM-DD HH:mm:ss'), now.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
    case 'month':
      return [now.startOf('month').format('YYYY-MM-DD HH:mm:ss'), now.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
    default:
      return dateRange.value ?? null
  }
}

function buildPayload(p = page.value): GetOutFlowInput {
  const range = computeRange()
  return {
    startTime: range ? range[0] : undefined,
    endTime: range ? range[1] : undefined,
    createStartTime: range ? range[0] : undefined,
    createEndTime: range ? range[1] : undefined,
    orderNo: query.orderNo,
    customerName: query.customerName,
    contactPerson: query.contactPerson,
    outType: query.outType,
    warehouseName: query.warehouseName,
    createUserName: query.createUserName,
    goodsOrCategory: query.goodsOrCategory,
    page: p,
    pageSize: pageSize.value
  }
}

function unwrapResponse(res: any) {
  // 兼容 { data: { result: {...} } } / { result: {...} } / 直接数据
  return res?.data?.result ?? res?.result ?? res?.data ?? {}
}

async function loadStats() {
  const res = await fetchOutFlowStats(buildPayload(1))
  const d: any = unwrapResponse(res)
  stats.ordersCount = d.ordersCount ?? d.OrdersCount ?? 0
  stats.goodsQuantity = d.goodsQuantity ?? d.GoodsQuantity ?? 0
  stats.goodsAmount = d.goodsAmount ?? d.GoodsAmount ?? 0
}

async function loadData(p?: number) {
  if (p) page.value = p
  const res = await fetchOutFlowPage(buildPayload(page.value))
  const wrapped: any = unwrapResponse(res)
  // 兼容 result.items / items / Items
  const d: any = wrapped?.result ?? wrapped
  const list = (d.items || d.Items || []) as any[]
  tableData.value = list.map((i: any) => ({
    billNo: i.billNo ?? i.BillNo,
    bizTime: i.bizTime ?? i.BizTime,
    outType: i.outType ?? i.OutType,
    customerName: i.customerName ?? i.CustomerName,
    goodsName: i.goodsName ?? i.GoodsName,
    warehouseName: i.warehouseName ?? i.WarehouseName,
    quantity: i.quantity ?? i.Quantity,
    amount: i.amount ?? i.Amount,
    operatorName: i.operatorName ?? i.OperatorName,
    makerName: i.makerName ?? i.MakerName,
    deptName: i.deptName ?? i.DeptName,
    makeTime: i.makeTime ?? i.MakeTime,
    auditorName: i.auditorName ?? i.AuditorName,
    auditTime: i.auditTime ?? i.AuditTime,
    remark: i.remark ?? i.Remark,
  }))
  total.value = d.total || d.Total || 0
  await loadStats()
}

function onQuickRange() {
  if (quickRange.value !== 'custom') {
    loadData(1)
  }
}

function reset() {
  quickRange.value = 'today'
  query.orderNo = undefined
  query.customerName = undefined
  query.contactPerson = undefined
  query.createUserName = undefined
  query.outType = undefined
  query.warehouseName = undefined
  query.goodsOrCategory = undefined
  dateRange.value = null
  loadData(1)
}

const stats = reactive({
  ordersCount: 0,
  goodsQuantity: 0,
  goodsAmount: 0,
})

function formatMoney(n: number) {
  return new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY', maximumFractionDigits: 2 }).format(n || 0)
}

async function onExport() {
  const rows = tableData.value
  const header = ['出库单号','出库时间','出库类型','客户名称','物品名称','仓库','数量','金额','经办人','制单人','所在部门','制单时间','审核人','审核时间','备注']
  const csv = [header.join(','), ...rows.map(r => [r.billNo,r.bizTime,r.outType,r.customerName,r.goodsName,r.warehouseName,r.quantity,r.amount,r.operatorName,r.makerName,r.deptName,r.makeTime,r.auditorName,r.auditTime,r.remark].map(v=>`"${(v??'').toString().replace(/"/g,'""')}"`).join(','))].join('\n')
  const blob = new Blob(["\ufeff" + csv], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `出库流水_${dayjs().format('YYYYMMDDHHmmss')}.csv`
  a.click()
  URL.revokeObjectURL(url)
}

watch(pageSize, () => loadData(1))

loadData(1)
</script>

<style scoped>
.ck-report { padding: 12px; }
.toolbar { display: flex; align-items: center; margin-bottom: 12px; flex-wrap: wrap; }
.cards { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-bottom: 12px; }
.card { text-align: center; }
.num { font-size: 22px; font-weight: 700; }
.label { color: #888; margin-top: 4px; font-size: 12px; }
.pager { margin-top: 10px; display: flex; justify-content: flex-end; }
</style>
